let movableAreaWidth = 0
let movableViewWidth = 0
const backgroundAudioManager = wx.getBackgroundAudioManager()
let currentSec = -1 // 当前的秒数
let duration = 0 // 当前歌曲的总时长，以秒为单位
let isMoving = false // 表示当前进度条是否在拖拽，解决：当进度条拖动时和onTimeUpdate事件有冲突的问题

Component({
    /**
     * 组件的属性列表
     */
    properties: {
        isSame: Boolean
    },

    /**
     * 组件的初始数据
     */
    data: {
        showTime: {
            currentTime: '00:00',
            totalTime: '00:00',
        },
        movableDistance: 0,
        progress: 0
    },

    lifetimes: {
        ready() {
            if (this.properties.isSame && this.data.showTime.totalTime === '00:00') {
                this._setTotalTime()
            }
            this._getMovableWidth()
            this._bindBGMEvent()
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 拖动过程中触发的事件
        onChange(event) {
            // 拖动中
            if (event.detail.source == 'touch') {
                this.data.progress = event.detail.x / (movableAreaWidth - movableViewWidth) * 100
                isMoving = true
            }
        },

        // 拖动结束触发的事件
        onTouchEnd() {
            const currentTimeFmt = this._dateFormat(Math.floor(backgroundAudioManager.currentTime))
            this.setData({
                progress: this.data.progress,
                ['showTime.currentTime']: currentTimeFmt.min + ':' + currentTimeFmt.sec
            })
            backgroundAudioManager.seek(duration * this.data.progress / 100)
            isMoving = false
        },

        // 获取可移动模块的宽度（容器+移动块）
        _getMovableWidth() {
            const query = this.createSelectorQuery()
            query.select('.movable-area').boundingClientRect()
            query.select('.movable-view').boundingClientRect()
            query.exec((rect) => {
                movableAreaWidth = rect[0].width
                movableViewWidth = rect[1].width
            })
        },

        // 绑定音频管理器的事件
        _bindBGMEvent() {
            backgroundAudioManager.onPlay(() => {
                console.log('onPlay')
                isMoving = false
                this.triggerEvent('musicPlay')
            })

            backgroundAudioManager.onStop(() => {
                console.log('onStop')
            })

            backgroundAudioManager.onPause(() => {
                console.log('Pause')
                this.triggerEvent('musicPause')
            })

            backgroundAudioManager.onWaiting(() => {
                console.log('onWaiting')
            })

            backgroundAudioManager.onCanplay(() => {
                console.log('onCanplay')
                if (typeof backgroundAudioManager.duration != 'undefined') {
                    this._setTotalTime()
                } else {
                    setTimeout(() => {
                        this._setTotalTime()
                    }, 1000)
                }
            })

            backgroundAudioManager.onTimeUpdate(() => {
                // console.log('onTimeUpdate')
                if (!isMoving) {
                    const currentTime = backgroundAudioManager.currentTime
                    const duration = backgroundAudioManager.duration
                    const sec = currentTime.toString().split('.')[0]
                    if (sec != currentSec) {
                        const currentTimeFmt = this._dateFormat(currentTime)
                        this.setData({
                            movableDistance: (movableAreaWidth - movableViewWidth) * currentTime / duration,
                            progress: currentTime / duration * 100,
                            ['showTime.currentTime']: `${currentTimeFmt.min}:${currentTimeFmt.sec}`,
                        })
                        currentSec = sec
                        // 联动歌词
                        this.triggerEvent('timeUpdate', {
                            currentTime
                        })
                    }
                }
            })

            backgroundAudioManager.onEnded(() => {
                console.log("onEnded")
                this.triggerEvent('musicEnd')
            })

            backgroundAudioManager.onError((res) => {
                console.error(res.errMsg)
                wx.showToast({
                    icon: 'error',
                    title: '错误:' + res.errCode,
                })
            })
        },

        // 设置歌曲的总时长
        _setTotalTime() {
            duration = backgroundAudioManager.duration
            const durationFmt = this._dateFormat(duration)
            this.setData({
                ['showTime.totalTime']: `${durationFmt.min}:${durationFmt.sec}`
            })
        },

        // 格式化时间
        _dateFormat(sec) {
            // 分钟
            const min = Math.floor(sec / 60)
            sec = Math.floor(sec % 60)
            return {
                'min': this._parseZero(min),
                'sec': this._parseZero(sec),
            }
        },

        // 补零
        _parseZero(sec) {
            return sec < 10 ? '0' + sec : sec
        }
    }
})